/**
 * 代号:隐无为 2017：厚溥
 * 文件名：UserDaoImpl.java
 * 创建人：柯栋
 * 日期：2017年10月25日
 * 修改人：
 * 描述：
 */
package org.setone.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.setone.dao.UserDao;
import org.setone.model.PageBean;
import org.setone.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * 用途：用户模块数据访问层逻辑
 */
@SuppressWarnings("all")
@Repository
public class UserDaoImpl  implements UserDao{

	@Autowired
	SessionFactory sessionFactory;
	
	@Override
	public List<User> queryAll() {
		return getHibernate().createQuery("from User").list();
	}

	@Override
	public User queryById(Integer id) {
		return getHibernate().get(User.class, id);
	}

	@Override
	public void save(User user) {
		getHibernate().save(user);
	}

	@Override
	public void delete(Integer id) {
		try {
			getHibernate().delete(queryById(id));
		} catch (Exception e) {
			throw new RuntimeException("id no exist, id 不存在");
		}
		
	}

	@Override
	public void update(User user) {
		getHibernate().update(user);
	}
	
	
	public Session getHibernate(){
		return sessionFactory.getCurrentSession();
	}

	@Override
	public User loginCheck(User user) {
		Query query =getHibernate().createQuery("from User u where u.name=? and u.pwd=?");
		query.setParameter(0, user.getName());
		query.setParameter(1, user.getPwd());
		List<User> list=query.list();
		return list.size()==0?null:list.get(0);
	}

	@Override
	public PageBean<User> queryPageList(Integer pageNum, Integer pageSize) {
		List<User> list=getHibernate().createQuery("from User").setFirstResult((pageNum-1)*pageSize).setMaxResults(pageSize).list();
		return new PageBean<User>(pageNum, pageSize, queryTotal(), list);
	}

	
	public Long queryTotal(){
		return (Long) getHibernate().createQuery("select count(*) from User").uniqueResult();
	}
	
	
	
}
